

import java.io.IOException;
import java.net.*;
import java.util.*;
import apmon.*;

public class TCPServer extends Thread {
	public static final int MaxAccepts = 100;
	public String serverName;

	private ServerSocket serverSocket;
	private int port;
	private ArrayList<TCPServiceThread> al;

	public static final String ConfigFileName = "config/mona.cfg";
	private Integer nPut=0, nGet=0, nFilter=0, nResize=0;
	private ApMon apm = null;
	
	public TCPServer(int port) {
		this.port = port;
		this.al = new ArrayList<TCPServiceThread>();

		try {
		//	apm = new ApMon(ConfigFileName);
		} catch (Exception e) {
			System.err.println("Eroare creare instanta ApMon: " + e);
			e.printStackTrace();
		}
	}
	
	public void run() {
		try {
			this.serverSocket = new ServerSocket(port);
		} catch (Exception e) {
			System.err.println("Exceptie la crearea ServerSocket-ului: " + e);
			e.printStackTrace();
			return;
		}
		
		for (int i = 0; i < MaxAccepts; i++) {
			System.out.println("[TCPServer] Accepting a new connection");

			Socket clientSocket = null;
			
			try {
				clientSocket = this.serverSocket.accept();
				TCPServiceThread tst = new TCPServiceThread(clientSocket);
				tst.setStat(nPut, nGet, nFilter, nResize);
				
				tst.start();
				this.al.add(tst);
			} catch (Exception e) {
				System.err.println("Eroare la accept: " + e);
				e.printStackTrace();
			}
			
			try {
				//apm.sendParameter("Servers", serverName, "nPut", nPut);
				//apm.sendParameter("Servers", serverName, "nGet", nGet);
				//apm.sendParameter("Servers", serverName, "nFilter", nFilter);
				//apm.sendParameter("Servers", serverName, "nResize", nResize);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		for (TCPServiceThread tst: this.al) {
			try {
				tst.join();
			} catch (Exception e) {}
		}
		
		try {
			this.serverSocket.close();
		} catch (Exception e) {
			System.err.println("ServerSocket close exception: " + e);
			e.printStackTrace();
		}
		
		apm.stopIt();
	}
	
	public static void main(String args[]) {
		TCPServer ts = new TCPServer(50001);
		ts.start();
		
		try {
			ts.join();
		} catch (Exception e) {}
	}
}
